package com.usian.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.article.feign.BehaviorFeign;
import com.usian.article.feign.UserFeign;
import com.usian.article.mapper.AuthorMapper;
import com.usian.article.mapper.CollectionMapper;
import com.usian.article.service.ArticleInfoService;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.article.pojos.ApCollection;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.behavior.pojos.ApLikesBehavior;
import com.usian.model.behavior.pojos.ApUnlikesBehavior;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.user.pojos.ApUserFollow;
import com.usian.utils.threadlocal.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ArticleInfoServiceImpl extends BaseServiceImpl<AuthorMapper, ApAuthor> implements ArticleInfoService {
    @Autowired
    private BehaviorFeign behaviorFeign;

    @Autowired
    private CollectionMapper collectionMapper;

    @Autowired
    private UserFeign userFeign;

    @Override
    public ResponseResult getArticleInfo(Long articleId, Integer authorId) {
        if (articleId == null) return paramError;
        Integer userId = ThreadLocalUtils.getUser();
        if (userId == null) return needLogin;
        Map<String, Boolean> resultMap = new HashMap<>();
        //查询到行为实体
        ApBehaviorEntry behaviorEntry = behaviorFeign.findByUserId(userId);
        ApUnlikesBehavior unLikesBehavior = behaviorFeign.getUnLikesBehavior(articleId, behaviorEntry.getId());
        resultMap.put("unlike", unLikesBehavior != null && unLikesBehavior.getType() == 0);
        ApLikesBehavior like = behaviorFeign.getLike(articleId, behaviorEntry.getId());
        resultMap.put("like", like != null && like.getOperation() == 0);
        ApCollection apCollection = collectionMapper.selectOne(Wrappers.<ApCollection>lambdaQuery().eq(ApCollection::getArticleId, articleId).eq(ApCollection::getEntryId, behaviorEntry.getId()));
        resultMap.put("collect", apCollection != null && apCollection.isCollectionArticle());
        ApAuthor author = getOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getId, authorId));
        ApUserFollow follow = userFeign.getFollow(userId, author.getUserId());
        resultMap.put("follow", follow != null);
        return ResponseResult.okResult(resultMap);
    }
}
